package org.jeecg.modules.supplierEvaluation.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.file.entity.ProcurementFile;
import org.jeecg.modules.file.service.IProcurementFileService;
import org.jeecg.modules.supplierEvaluation.Vo.SupplierEvaluationStatsVo;
import org.jeecg.modules.supplierEvaluation.Vo.SupplierEvaluationVo;
import org.jeecg.modules.supplierEvaluation.entity.SupplierEvaluation;
import org.jeecg.modules.supplierEvaluation.mapper.SupplierEvaluationMapper;
import org.jeecg.modules.supplierEvaluation.service.ISupplierEvaluationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j

@Service
public class SupplierEvaluationServiceImpl extends ServiceImpl<SupplierEvaluationMapper, SupplierEvaluation> implements ISupplierEvaluationService {

    @Autowired
    private IProcurementFileService procurementFileService;
    @Override
    public List<SupplierEvaluation> getHistoryBySupplierId(String supplierId) {
        return lambdaQuery()
                .eq(SupplierEvaluation::getSupplierId, supplierId)
                .orderByDesc(SupplierEvaluation::getEvaluationTime)
                .list();
    }

    @Override
    public List<SupplierEvaluation> getLatestEvaluationByBidId(String bidId){
        return lambdaQuery()
                .eq(SupplierEvaluation::getBidId, bidId)
                .orderByDesc(SupplierEvaluation::getEvaluationTime)
                .last("limit 1")
                .list();
    }

    @Override
    public List<SupplierEvaluation> getAllEvaluationByBidId(String bidId){
        return lambdaQuery()
                .eq(SupplierEvaluation::getBidId, bidId)
                .list();
    }


    @Override
    public BigDecimal calculateAverageScore(String supplierId) {
        // 获取供应商的所有评价记录，按purchaseId和创建时间降序排序
        List<SupplierEvaluation> evaluations = lambdaQuery()
                .eq(SupplierEvaluation::getSupplierId, supplierId)
                .orderByDesc(SupplierEvaluation::getPurchaseId)
                .orderByDesc(SupplierEvaluation::getCreateTime)
                .list();

        // 如果没有评价记录，返回0
        if (evaluations == null || evaluations.isEmpty()) {
            return BigDecimal.ZERO;
        }

        // 按purchaseId分组，每组只保留最新的一条评价
        Map<String, SupplierEvaluation> latestEvaluationsByGroup = new LinkedHashMap<>();
        for (SupplierEvaluation evaluation : evaluations) {
            String purchaseId = evaluation.getPurchaseId();
            // 由于已经按时间降序排序，第一次遇到的就是该purchaseId的最新记录
            if (!latestEvaluationsByGroup.containsKey(purchaseId)) {
                latestEvaluationsByGroup.put(purchaseId, evaluation);
            }
        }

        // 计算总分
        BigDecimal totalScore = BigDecimal.ZERO;
        for (SupplierEvaluation evaluation : latestEvaluationsByGroup.values()) {
            if (evaluation.getTotalScore() != null) {
                totalScore = totalScore.add(evaluation.getTotalScore());
            }
        }

        // 计算平均分，保留两位小数
        int validGroupCount = latestEvaluationsByGroup.size();
        BigDecimal averageScore = validGroupCount > 0 ?
                totalScore.divide(new BigDecimal(validGroupCount), 2, BigDecimal.ROUND_HALF_UP) :
                BigDecimal.ZERO;

        return averageScore;
    }

    @Transactional
    public boolean add(SupplierEvaluation evaluation) {
        try {
            // 检查evaluation对象是否为空
            if (evaluation == null) {
                throw new IllegalArgumentException("评价对象不能为空");
            }

            // 检查必填字段
            if (evaluation.getSupplierId() == null || evaluation.getProjectName() == null) {
                throw new IllegalArgumentException("供应商ID和项目名称不能为空");
            }

            // 调用父类的save方法并返回实际结果
            boolean result = this.save(evaluation);

            // 记录保存结果日志
            if (result) {
                log.info("成功保存供应商评价: 供应商ID={}, 项目名称={}",
                        evaluation.getSupplierId(), evaluation.getProjectName());
            } else {
                log.error("保存供应商评价失败: 供应商ID={}, 项目名称={}",
                        evaluation.getSupplierId(), evaluation.getProjectName());
            }

            return result;
        } catch (Exception e) {
            // 记录异常日志
            log.error("保存供应商评价时发生异常: {}", e.getMessage(), e);
            // 重新抛出异常，让上层调用者能够捕获处理
            throw e;
        }
    }

    /**
     * 根据供应商ID获取供应商所有项目最新评价
     * @param supplierId
     * @return
     */
    public List<SupplierEvaluation> getLatestEvaluationBySupplierId(String supplierId){
        // 获取供应商的所有评价记录
        List<SupplierEvaluation> evaluations = getHistoryBySupplierId(supplierId);

        if (evaluations == null || evaluations.isEmpty()) {
            return null;
        }

        // 按 bidId 分组，并在每组中取 evaluationTime 最新的记录
        Map<String, SupplierEvaluation> latestEvaluationsByBid = evaluations.stream()
                .filter(e -> e.getBidId() != null && e.getEvaluationTime() != null && e.getTotalScore() != null)
                .collect(Collectors.toMap(
                        SupplierEvaluation::getBidId, // key: bidId（代表一个项目/投标）
                        e -> e,                       // value: 评价记录
                        (e1, e2) -> e1.getEvaluationTime().after(e2.getEvaluationTime()) ? e1 : e2 // 取时间更新的
                ));
        List<SupplierEvaluation>  latestEvaluations= new ArrayList<>(latestEvaluationsByBid.values());

        return latestEvaluations;
    }

    @Override
    public LinkedHashMap<String, List<SupplierEvaluationVo>> getBySupplierIdGroupByPurchaseId(String supplierId) {
        // 根据供应商ID查询所有评价记录，按purchaseId和评价时间排序
        List<SupplierEvaluation> evaluations = lambdaQuery()
                .eq(SupplierEvaluation::getSupplierId, supplierId)
                .orderByDesc(SupplierEvaluation::getPurchaseId)
                .orderByDesc(SupplierEvaluation::getCreateTime)
                .list();

        // 使用LinkedHashMap保证插入顺序
        LinkedHashMap<String, List<SupplierEvaluationVo>> groupedEvaluations = new LinkedHashMap<>();

        //
        for (SupplierEvaluation evaluation : evaluations) {
            SupplierEvaluationVo supplierEvaluationVo = new SupplierEvaluationVo();
            String purchaseId = evaluation.getPurchaseId();
            if (!groupedEvaluations.containsKey(purchaseId)) {
                groupedEvaluations.put(purchaseId, new ArrayList<>());
            }
            List<ProcurementFile> file = procurementFileService.getFilesByBiz(evaluation.getId(),"evaluation");
            supplierEvaluationVo.setProcurementFile(file);
            supplierEvaluationVo.setSupplierEvaluation(evaluation);
            //把找到的文件、放入SupplierEvaluationVo，
            groupedEvaluations.get(purchaseId).add(supplierEvaluationVo);
        }

        return groupedEvaluations;
    }

    @Override
    public SupplierEvaluationStatsVo getSupplierEvaluationStats(String supplierId) {
        // 获取按purchaseId分组的评价记录，每个purchaseId只保留最新的一条
        LinkedHashMap<String, List<SupplierEvaluationVo>> groupedEvaluations = getBySupplierIdGroupByPurchaseId(supplierId);

        // 如果没有评价记录，返回空的统计信息
        if (groupedEvaluations.isEmpty()) {
            SupplierEvaluationStatsVo statsVo = new SupplierEvaluationStatsVo();
            statsVo.setAverageScore(BigDecimal.ZERO);
            statsVo.setGroupCount(0);
            statsVo.setOnTimeRate(BigDecimal.ZERO);
            statsVo.setQualityStandardRate(BigDecimal.ZERO);
            return statsVo;
        }

        // 统计相关数据
        BigDecimal totalScore = BigDecimal.ZERO;
        int onTimeCount = 0;
        int qualityStandardCount = 0;
        int groupCount = groupedEvaluations.size();

        for (List<SupplierEvaluationVo> evalList : groupedEvaluations.values()) {
            if (!evalList.isEmpty()) {
                // 获取每个组的第一条记录（因为已经按时间降序排列，所以第一条是最新的）
                SupplierEvaluationVo latestEval = evalList.get(0);

                // 累计总分
                if (latestEval.getTotalScore() != null) {
                    totalScore = totalScore.add(latestEval.getTotalScore());
                }

                // 统计按时完成数量（0表示是，1表示否）
                if (latestEval.getOnTimeCompletion() != null && latestEval.getOnTimeCompletion() == 0) {
                    onTimeCount++;
                }

                // 统计质量达标数量（0表示是，1表示否）
                if (latestEval.getQualityStandard() != null && latestEval.getQualityStandard() == 0) {
                    qualityStandardCount++;
                }
            }
        }

        // 计算平均分
        BigDecimal averageScore = totalScore.divide(
                new BigDecimal(groupCount),
                2, BigDecimal.ROUND_HALF_UP);

        // 计算完工率：按时完成数量 / 组数
        BigDecimal onTimeRate = BigDecimal.ZERO;
        if (groupCount > 0) {
            onTimeRate = new BigDecimal(onTimeCount)
                    .divide(new BigDecimal(groupCount), 2, BigDecimal.ROUND_HALF_UP)
                    .multiply(new BigDecimal(100));
        }

        // 计算质量达标率：质量达标数量 / 组数
        BigDecimal qualityStandardRate = BigDecimal.ZERO;
        if (groupCount > 0) {
            qualityStandardRate = new BigDecimal(qualityStandardCount)
                    .divide(new BigDecimal(groupCount), 2, BigDecimal.ROUND_HALF_UP)
                    .multiply(new BigDecimal(100));
        }

        // 构建返回对象
        SupplierEvaluationStatsVo statsVo = new SupplierEvaluationStatsVo();
        statsVo.setAverageScore(averageScore);
        statsVo.setGroupCount(groupCount);
        statsVo.setOnTimeRate(onTimeRate);
        statsVo.setQualityStandardRate(qualityStandardRate);

        return statsVo;
    }
}
